import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Toast, Tabs, Empty } from '@nutui/nutui-react';
import { useSelector } from 'react-redux';
import { api } from '@/api/api';
import useCountdown from '@/hooks/useCountdown';
import { formatPrice } from '@/utils/formatPrice';
import './index.less';
import noData from '@/assets/images/no-data.png'
// 倒计时显示组件
const CountdownDisplay = ({ order }) => {
    const [formattedTime, isExpired] = useCountdown(order.timeout, null); // 暂时不处理超时回调

    if (isExpired) {
        return (
            <div className="countdown-display expired">
                <span className="expired-text">已超时</span>
            </div>
        );
    }

    return (
        <div className="countdown-display">
            <span className="countdown-text">剩余时间 {formattedTime}</span>
        </div>
    );
};

const OrdersPage = () => {
    const navigate = useNavigate();
    const [searchParams] = useSearchParams();
    const userInfo = useSelector(state => state.user.userInfo);
    const shopId = useSelector(state => state.shop.shopId);
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('0');
    const [payingOrder, setPayingOrder] = useState(null);

    const getStatusText = (orderStatus, payStatus) => {
        const statusMap = {
            '0': { text: '待付款', color: '#ff6b35', bg: '#fff2e8' },
            '1': { text: '已支付', color: '#28a745', bg: '#d4edda' },
            '2': { text: '退款中', color: '#ffc107', bg: '#fff3cd' },
            '3': { text: '已退款', color: '#6c757d', bg: '#e9ecef' }
        };
        
        // 优先显示支付状态，如果没有则显示订单状态
        const status = payStatus !== null ? payStatus.toString() : orderStatus.toString();
        return statusMap[status] || statusMap['0'];
    };

    const formatTime = (timeString) => {
        if (!timeString) return '';
        
        try {
            const date = new Date(timeString);
            const now = new Date();
            const diffTime = now - date;
            const diffMinutes = Math.floor(diffTime / (1000 * 60));
            const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
            const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
            
            if (diffMinutes < 1) {
                return '刚刚';
            }
            else if (diffMinutes < 60) {
                return `${diffMinutes}分钟前`;
            }
            else if (diffHours < 24) {
                return `${diffHours}小时前`;
            }
            else if (diffDays === 1) {
                return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
            }
            else if (diffDays < 7) {
                const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                const weekday = weekdays[date.getDay()];
                return `${weekday} ${date.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                })}`;
            }
            else if (date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth()) {
                return date.toLocaleDateString('zh-CN', { 
                    month: 'short', 
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            }
            else {
                return date.toLocaleDateString('zh-CN', { 
                    year: 'numeric',
                    month: 'short', 
                    day: 'numeric'
                });
            }
        } catch (error) {
            console.error('时间格式化错误:', error);
            return timeString;
        }
    };

    const orderStatusConfig = [
        { value: '0', label: '待付款' },
        { value: '1', label: '已支付' },
        { value: '2', label: '退款中' },
        { value: '3', label: '已退款' }
    ];

    const fetchOrders = async (payStatus = '0') => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        try {
            setLoading(true);
            
            const response = await api.getMainOrder({
                shopId,
                userId: userInfo.userId,
                payStatus: payStatus
            });

            if (response.code === 200) {
                setOrders(response.data || []);
            }
        } catch (error) {
            Toast.show('获取订单列表失败');
        } finally {
            setLoading(false);
        }
    };

    const handleViewOrderDetail = (orderNo, orderStatus, payStatus) => {
        navigate(`/orders/detail/${orderNo}?orderStatus=${orderStatus}&payStatus=${payStatus}`);
    };

    const handlePayOrder = async (order) => {
        if (order.totalAmount === 0) {
            Toast.show('0元订单无需支付，订单已完成！');
            fetchOrders(activeTab);
            return;
        }

        if (!order.prepayId) {
            Toast.show('订单支付信息异常');
            return;
        }

        try {
            setPayingOrder(order.id);
            const res = await api.getPaySign(order.prepayId);
            const payConfig = res.data;
            window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
                "appId": payConfig.appId,  
                "timeStamp": payConfig.timestamp,
                "nonceStr": payConfig.nonceStr, 
                "package": `prepay_id=${payConfig.prepayId}`,
                "signType": "RSA",   
                "paySign": payConfig.paySign,
            }, (res) => {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    Toast.show('支付成功！');
                    fetchOrders(activeTab);
                }
            });
        } catch (error) {
            console.error('支付失败:', error);
            Toast.show('支付失败，请重试');
        } finally {
            setPayingOrder(null);
        }
    };

    const handleTimeUp = (orderId) => {
        setOrders(prev => prev.map(order => 
            order.id === orderId 
                ? { 
                    ...order, 
                    payStatus: 1, // 已取消状态
                    cancelReason: 1, // TIMEOUT_CANCEL
                    orderStatus: 1 // 更新订单状态
                  }
                : order
        ));
        
        Toast.show('订单支付超时，已自动取消');
    };

    const isOrderExpired = (order) => {
        if (!order.timeout) return false;
        const orderCreateTime = new Date(order.createTime).getTime();
        const timeoutMs = order.timeout * 1000; 
        const expireTime = orderCreateTime + timeoutMs;
        const currentTime = new Date().getTime();
        
        return currentTime >= expireTime;
    };

    useEffect(() => {
        const tabParam = searchParams.get('tab');
        if (tabParam && ['0', '1', '2', '3'].includes(tabParam)) {
            setActiveTab(tabParam);
            fetchOrders(tabParam);
        } else {
            fetchOrders();
        }
    }, [userInfo, searchParams]);

    const handleTabChange = (value) => {
        setActiveTab(value);
        navigate(`/orders?tab=${value}`, { replace: true });
        fetchOrders(value);
    };

    return (
        <div className="orders-page" style={{minHeight: '100vh'}}>
            <Tabs 
                value={activeTab} 
                onChange={handleTabChange}
                className="order-tabs"
                activeType="smile"
            >
                {orderStatusConfig.map((status) => (
                    <Tabs.TabPane key={status.value} title={status.label} />
                ))}
            </Tabs>

            <div className="orders-content">
                {loading ? (
                    <div className="loading">加载中...</div>
                ) : orders.length > 0 ? (
                    <div className="orders-list">
                        {orders.map((order) => (
                            <div key={order.id} className="order-card">
                                                             <div className="order-header">
                                    <div className="order-info-left">
                                        <span className="order-no">{order.orderNo}</span>
                                        <span className="order-time">{formatTime(order.createTime)}</span>
                                    </div>
                                    <div className="order-status-section">
                                        <div className="order-status-badge">
                                            {getStatusText(order.orderStatus, order.payStatus).text}
                                        </div>
                                        {activeTab === '0' && String(order.payStatus) === '0' && order.timeout && order.timeout > 0 && (
                                            <CountdownDisplay order={order} />
                                        )}
                                    </div>
                                </div>
                                <div className="order-content">
                                    <div className="order-details">
                                        <div className="amount-section">
                                            <span className="amount-label">订单金额</span>
                                            <span className="amount-value">{formatPrice(order.totalAmount)}</span>
                                        </div>
                                        {order.remark && (
                                            <div className="order-remark">
                                                <span className="remark-label">备注：</span>
                                                <span className="remark-text">{order.remark}</span>
                                            </div>
                                        )}
                                    </div>
                                    
                                    <div className="button-group">
                                        {activeTab === '0' && String(order.payStatus) === '0' && order.totalAmount > 0 && !isOrderExpired(order) && (
                                            <Button 
                                                type="primary" 
                                                size="small"
                                                disabled={payingOrder === order.id}
                                                loading={payingOrder === order.id}
                                                onClick={() => handlePayOrder(order)}
                                                className="pay-button"
                                            >
                                                {payingOrder === order.id ? '支付中...' : '立即支付'}
                                            </Button>
                                        )}
                                        
                                        <button 
                                            className="view-detail-btn"
                                            onClick={() => handleViewOrderDetail(order.orderNo, order.orderStatus, order.payStatus)}
                                        >
                                            查看详情
                                        </button>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <Empty 
                        image={
                            <img
                                src={noData}
                                alt=""
                            />
                        } 
                        description="暂无订单" 
                    />
                )}
            </div>
        </div>
    );
};

export default OrdersPage;